package com.ysc.task.util;

import com.cronutils.descriptor.CronDescriptor;
import com.cronutils.model.Cron;
import com.cronutils.model.CronType;
import com.cronutils.model.definition.CronDefinition;
import com.cronutils.model.definition.CronDefinitionBuilder;
import com.cronutils.model.time.ExecutionTime;
import com.cronutils.parser.CronParser;
import org.springframework.scheduling.support.CronExpression;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Optional;

/**
 * Version: 1.0
 * Class Name: CronUtils
 * Description: TODO(一句话描述功能)
 * Author: ysc
 * Date: 2024/4/1 9:19
 */
@Component
public class CronUtils {
    /**
     * 解释cron表达式
     */
    public static String describeCron(String expression) {
        CronDefinition cronDefinition = CronDefinitionBuilder.instanceDefinitionFor(CronType.SPRING);
        CronParser parser = new CronParser(cronDefinition);
        Cron cron = parser.parse(expression);
        //设置语言
        CronDescriptor descriptor = CronDescriptor.instance(Locale.CHINESE);
        return descriptor.describe(cron);
    }
    /**
     * 解析cron转化为执行时间
     * @return
     */
    public static String parseCronToExeTime(String expression) {
        CronDefinition cronDefinition = CronDefinitionBuilder.instanceDefinitionFor(CronType.SPRING);
        CronParser parser = new CronParser(cronDefinition);
        Cron cron = parser.parse(expression);
        ExecutionTime exeTime=ExecutionTime.forCron(cron);
        ZonedDateTime now = ZonedDateTime.now();
        //根据当前时间获取下次执行时间
        ZonedDateTime next = exeTime.nextExecution(now).get();
        DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
        return next.format(format);
    }

    /**
     * 检查cron表达式的合法性
     *
     * @param cron cron exp
     * @return true if valid
     */
    public static boolean checkCronValid(String cron) {
        try {
            return CronExpression.isValidExpression(cron);
        } catch (Exception e) {
            System.out.println(String.format("cron=%s not valid", cron));
            return false;
        }
    }
}